#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CodeBuddy登录分析脚本
分析登录失败的原因并提供解决方案
"""

import requests
from urllib.parse import unquote, parse_qs, urlparse
import json
import base64

def analyze_login_failure():
    """分析登录失败的原因"""
    print("🔍 CodeBuddy登录失败分析")
    print("=" * 50)
    
    # 测试结果分析
    print("📊 测试结果:")
    print("  - HTTP状态码: 400 (Bad Request)")
    print("  - 获取到cookies: KC_STATE_CHECKER")
    print("  - 结果: 登录失败")
    
    print("\n❌ 失败原因分析:")
    print("1. **URL参数过期**: session_code和execution参数可能已过期")
    print("2. **请求格式问题**: 可能缺少必要的参数或格式不正确")
    print("3. **Session状态**: 需要先建立有效的Keycloak session")
    print("4. **CSRF保护**: 可能需要CSRF token")
    
    # 解析URL参数
    login_url = "https://www.codebuddy.ai/auth/realms/copilot/login-actions/authenticate?session_code=xxjnB7YjKIl_ajufRD5EqDl_yPvKhdn94um5DLP2DUo&execution=fddd3124-02c5-4e2e-9e11-2849f14b804f&client_id=console&tab_id=6MTzVOJ10oI&client_data=eyJydSI6Imh0dHBzOi8vd3d3LmNvZGVidWRkeS5haS9jb25zb2xlL2FjY291bnRzLy5hcGlzaXgvcmVkaXJlY3QiLCJydCI6ImNvZGUiLCJzdCI6ImFhNzllMDRiOTYzNDBkMTRhZjcwNGZjYWFiYzM5NWZkIn0"
    
    parsed_url = urlparse(login_url)
    params = parse_qs(parsed_url.query)
    
    print("\n🔗 URL参数分析:")
    for key, value in params.items():
        print(f"  - {key}: {value[0]}")
    
    # 解码client_data
    try:
        client_data_encoded = params.get('client_data', [''])[0]
        if client_data_encoded:
            client_data_decoded = base64.b64decode(client_data_encoded + '==').decode('utf-8')
            client_data_json = json.loads(client_data_decoded)
            print(f"\n📋 Client Data解码:")
            for key, value in client_data_json.items():
                print(f"  - {key}: {value}")
    except Exception as e:
        print(f"\n❌ Client Data解码失败: {e}")

def get_fresh_login_url():
    """获取新的登录URL和参数"""
    print("\n🔄 尝试获取新的登录参数...")
    
    session = requests.Session()
    session.headers.update({
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"
    })
    
    try:
        # 访问控制台页面，应该会重定向到登录页
        response = session.get("https://www.codebuddy.ai/console", allow_redirects=True)
        
        print(f"📊 状态码: {response.status_code}")
        print(f"🔗 最终URL: {response.url}")
        
        if "auth/realms" in response.url and "login-actions" in response.url:
            print("✅ 成功获取到新的登录URL")
            
            # 解析新的URL参数
            parsed_url = urlparse(response.url)
            params = parse_qs(parsed_url.query)
            
            print("\n🆕 新的URL参数:")
            for key, value in params.items():
                print(f"  - {key}: {value[0]}")
            
            return response.url, session
        else:
            print("❌ 未能获取到登录URL")
            return None, None
            
    except Exception as e:
        print(f"❌ 获取登录URL失败: {e}")
        return None, None

def test_with_fresh_params():
    """使用新参数测试登录"""
    print("\n🚀 使用新参数测试登录...")
    
    login_url, session = get_fresh_login_url()
    if not login_url:
        print("❌ 无法获取新的登录参数")
        return False
    
    # 准备登录数据
    data = "username=154hdgrkk7%40dpmurt.my&password=5gHpr0V%21&credentialId="
    
    headers = {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "content-type": "application/x-www-form-urlencoded",
        "cache-control": "max-age=0",
        "sec-fetch-dest": "document",
        "sec-fetch-mode": "navigate",
        "sec-fetch-site": "same-origin",
        "sec-fetch-user": "?1",
        "upgrade-insecure-requests": "1"
    }
    
    try:
        response = session.post(
            login_url,
            headers=headers,
            data=data,
            allow_redirects=True,
            timeout=15
        )
        
        print(f"📊 状态码: {response.status_code}")
        print(f"🔗 最终URL: {response.url}")
        
        if response.status_code == 200:
            if "console" in response.url and "account" in response.url:
                print("✅ 登录成功！")
                return True
            elif "error" in response.url.lower():
                print("❌ 登录失败 - 重定向到错误页面")
                return False
            else:
                print("⚠️ 登录状态不确定")
                return None
        else:
            print(f"❌ HTTP错误: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ 登录测试失败: {e}")
        return False

def main():
    """主函数"""
    print("🎯 CodeBuddy登录问题诊断工具")
    print("=" * 60)
    
    # 分析失败原因
    analyze_login_failure()
    
    # 尝试获取新参数并测试
    test_result = test_with_fresh_params()
    
    print("\n" + "=" * 60)
    print("📋 诊断结果总结")
    print("=" * 60)
    
    print("\n🔍 问题诊断:")
    print("1. 原始请求返回HTTP 400错误")
    print("2. 这通常表示URL参数已过期或格式不正确")
    print("3. Keycloak认证系统需要有效的session参数")
    
    print("\n💡 解决方案:")
    print("1. **获取新参数**: 先访问登录页面获取新的session_code和execution")
    print("2. **完整流程**: 模拟完整的浏览器登录流程")
    print("3. **Session管理**: 正确处理cookies和session状态")
    print("4. **错误处理**: 添加重试机制和错误恢复")
    
    if test_result is True:
        print("\n✅ 使用新参数登录成功！")
    elif test_result is False:
        print("\n❌ 即使使用新参数也无法登录")
    else:
        print("\n⚠️ 登录状态不确定，需要进一步调试")
    
    print("\n🎯 结论:")
    print("提供的fetch请求**无法直接成功登录**，因为:")
    print("- URL中的动态参数已过期")
    print("- 需要先建立有效的session")
    print("- 可能需要处理CSRF保护机制")

if __name__ == "__main__":
    main()